'use client';

import { Suspense, useState } from 'react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  FileSpreadsheet,
  PieChart as PieChartIcon,
  LineChart as LineChartIcon,
  Building2,
  Receipt,
  TrendingUp,
  ArrowUpRight,
  Download,
  Calendar,
} from 'lucide-react';
import { formatMoney, calculateProgress } from '@/lib/utils';
import { prisma } from '@/lib/prisma';
import {
  PieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from 'recharts';
import { startOfMonth, format, subMonths, isWithinInterval } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { toast } from '@/components/ui/use-toast';
import { DateRange } from 'react-day-picker';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { Calendar as CalendarIcon } from '@/components/ui/calendar';

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用'
} as const;

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

const statusMap = {
  active: '进行中',
  completed: '已完工',
  paused: '已暂停'
} as const;

async function SummaryAnalysis() {
  // 获取所有工地信息
  const sites = await prisma.site.findMany({
    include: {
      expenses: {
        select: {
          type: true,
          amount: true,
          paymentDate: true,
        },
      },
    },
  });

  // 计算工地状态统计
  const siteStatusStats = sites.reduce((acc, site) => {
    acc[site.status] = (acc[site.status] || 0) + 1;
    return acc;
  }, {} as Record<string, number>);

  // 计算总合同金额和总支出
  const totalContractAmount = sites.reduce((acc, site) => acc + site.contractAmount, 0);
  const totalExpenses = sites.reduce((acc, site) => 
    acc + site.expenses.reduce((sum, expense) => sum + expense.amount, 0), 0);

  // 按类型统计支出
  const expensesByType = sites.reduce((acc, site) => {
    site.expenses.forEach(expense => {
      acc[expense.type] = (acc[expense.type] || 0) + expense.amount;
    });
    return acc;
  }, {} as Record<string, number>);

  // 转换为饼图数据
  const pieData = Object.entries(expensesByType).map(([type, amount]) => ({
    name: expenseTypeMap[type as keyof typeof expenseTypeMap],
    value: amount,
  }));

  // 获取最近6个月的趋势数据
  const today = new Date();
  const monthsRange = Array.from({ length: 6 }, (_, i) => {
    const date = subMonths(today, i);
    return {
      start: startOfMonth(date),
      label: format(date, 'yyyy年MM月', { locale: zhCN }),
    };
  }).reverse();

  const trendData = monthsRange.map(({ start, label }) => {
    const endDate = new Date(start.getFullYear(), start.getMonth() + 1, 0);
    const monthExpenses = sites.flatMap(site => 
      site.expenses.filter(expense => 
        isWithinInterval(expense.paymentDate, { start, end: endDate })
      )
    );

    const total = monthExpenses.reduce((sum, expense) => sum + expense.amount, 0);

    return {
      month: label,
      amount: total,
    };
  });

  // 计算进行中的工地数量
  const activeSites = sites.filter(site => site.status === 'active').length;

  // 计算平均支出
  const averageExpensePerSite = totalExpenses / sites.length;

  return (
    <div className="space-y-6">
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总合同金额</CardTitle>
            <Building2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(totalContractAmount)}</div>
            <p className="text-xs text-muted-foreground">
              {sites.length} 个工地
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总支出金额</CardTitle>
            <Receipt className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(totalExpenses)}</div>
            <div className="mt-2 h-2 w-full rounded-full bg-secondary">
              <div
                className="h-2 rounded-full bg-primary"
                style={{ width: `${calculateProgress(totalExpenses, totalContractAmount)}%` }}
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">进行中工地</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{activeSites}</div>
            <p className="text-xs text-muted-foreground">
              占比 {((activeSites / sites.length) * 100).toFixed(1)}%
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">平均支出</CardTitle>
            <ArrowUpRight className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(averageExpensePerSite)}</div>
            <p className="text-xs text-muted-foreground">每个工地</p>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle>支出类型分布</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[300px]">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={pieData}
                    cx="50%"
                    cy="50%"
                    labelLine={false}
                    label={({ name, percent }) => `${name} ${(percent * 100).toFixed(1)}%`}
                    outerRadius={100}
                    fill="#8884d8"
                    dataKey="value"
                  >
                    {pieData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(value: number) => formatMoney(value)} />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div className="mt-4 space-y-2">
              {pieData.map((entry, index) => (
                <div key={entry.name} className="flex items-center justify-between">
                  <div className="flex items-center">
                    <div
                      className="w-3 h-3 rounded-full mr-2"
                      style={{ backgroundColor: COLORS[index % COLORS.length] }}
                    />
                    <span>{entry.name}</span>
                  </div>
                  <span className="font-medium">{formatMoney(entry.value)}</span>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>近期支出趋势</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="h-[300px]">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={trendData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="month" />
                  <YAxis />
                  <Tooltip formatter={(value: number) => formatMoney(value)} />
                  <Legend />
                  <Line
                    type="monotone"
                    dataKey="amount"
                    name="支出金额"
                    stroke="#8884d8"
                    strokeWidth={2}
                  />
                </LineChart>
              </ResponsiveContainer>
            </div>
            <div className="mt-4">
              <div className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">最近6个月总支出</span>
                <span className="font-medium">
                  {formatMoney(trendData.reduce((sum, item) => sum + item.amount, 0))}
                </span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 md:grid-cols-3">
        {Object.entries(statusMap).map(([status, label]) => (
          <Card key={status}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">{label}工地</CardTitle>
              <Building2 className="h-4 w-4 text-muted-foreground" />
            </CardHeader>
            <CardContent>
              <div className="text-2xl font-bold">{siteStatusStats[status] || 0}</div>
              <p className="text-xs text-muted-foreground">
                占比 {(((siteStatusStats[status] || 0) / sites.length) * 100).toFixed(1)}%
              </p>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}

export default function SummaryReportPage() {
  const [date, setDate] = useState<DateRange | undefined>({
    from: subMonths(new Date(), 6),
    to: new Date(),
  });

  const handleExport = async () => {
    try {
      const params = new URLSearchParams();
      if (date?.from) {
        params.append('from', date.from.toISOString());
      }
      if (date?.to) {
        params.append('to', date.to.toISOString());
      }

      const response = await fetch(`/api/reports/export?${params.toString()}`);
      if (!response.ok) throw new Error('导出失败');

      const contentDisposition = response.headers.get('content-disposition');
      const filename = contentDisposition?.split('filename=')[1]?.replace(/"/g, '') || '工程支出报表.xlsx';

      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      toast({
        title: '导出成功',
        description: '报表已成功导出',
      });
    } catch (error) {
      console.error('导出失败:', error);
      toast({
        variant: 'destructive',
        title: '导出失败',
        description: '请稍后重试',
      });
    }
  };

  return (
    <main className="container mx-auto p-4 space-y-4">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">总览报表</h1>
          <p className="text-muted-foreground">
            查看工程项目的整体财务状况
          </p>
        </div>
        <div className="flex gap-2">
          <Popover>
            <PopoverTrigger asChild>
              <Button variant="outline" className="w-[280px] justify-start text-left font-normal">
                <Calendar className="mr-2 h-4 w-4" />
                {date?.from ? (
                  date.to ? (
                    <>
                      {format(date.from, 'yyyy年MM月dd日')} - {format(date.to, 'yyyy年MM月dd日')}
                    </>
                  ) : (
                    format(date.from, 'yyyy年MM月dd日')
                  )
                ) : (
                  <span>选择日期范围</span>
                )}
              </Button>
            </PopoverTrigger>
            <PopoverContent className="w-auto p-0" align="start">
              <CalendarIcon
                mode="range"
                selected={date}
                onSelect={setDate}
                numberOfMonths={2}
                locale={zhCN}
              />
            </PopoverContent>
          </Popover>
          <Button variant="outline" asChild>
            <Link href="/reports/by-type">
              <PieChartIcon className="mr-2 h-4 w-4" />
              类型分析
            </Link>
          </Button>
          <Button variant="outline" asChild>
            <Link href="/reports/by-time">
              <LineChartIcon className="mr-2 h-4 w-4" />
              趋势分析
            </Link>
          </Button>
          <Button onClick={handleExport}>
            <Download className="mr-2 h-4 w-4" />
            导出报表
          </Button>
        </div>
      </div>

      <Suspense fallback={<div>加载中...</div>}>
        <SummaryAnalysis />
      </Suspense>
    </main>
  );
} 